const express = require('express');
const path = require('path');
const fs = require('fs');
const time = require('time-stamp');
const app = express();
app.listen(3000, () => {
  console.log('服务器已开启')
});
const router = express.Router();
//读取文件
let data = JSON.parse(fs.readFileSync(path.join(__dirname, 'persons.json')))

app.use(express.urlencoded({extended: false}))

app.use(express.static(path.join(__dirname, '../view')))
//渲染register
app.get('/register', (req, res) => {
  res.sendFile(path.join(__dirname, '../view/register.html'))
})

//注册
app.post('/register', (req, res) => {
  let {username,password,password2} = req.body
  let a = data.find(function (item) {
    return username == item.username;
  })
  if (a) {
    res.send('用户名已存在')
  } else if (password == password2) {
    data.push({username,password,time: time('YYYY年MM月DD日 HH:mm:ss')});
    fs.writeFileSync(path.join(__dirname, "persons.json"), JSON.stringify(data));
    res.send('注册成功');
  } else {
    res.send('二次密码不一致')
  }
})
module.exports = router;